﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace GUI
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string searchurl = "http://www.dvdxml.com/search.php?q={0}&t=1";

        public MainWindow()
        {
            InitializeComponent();

            if (this.txtMovieFolder.Text.Length > 0)
            {
                this.LoadMovies(this.txtMovieFolder.Text);
            }
        }

        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowser = new System.Windows.Forms.FolderBrowserDialog();

            if (this.txtMovieFolder.Text.Length > 0)
            {
                if (System.IO.Directory.Exists(this.txtMovieFolder.Text))
                {
                    folderBrowser.SelectedPath = this.txtMovieFolder.Text;
                }
            }

            if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.LoadMovies(folderBrowser.SelectedPath);
                this.txtMovieFolder.Text = folderBrowser.SelectedPath;

                GUI.Properties.Settings.Default.Save();
            }
        }

        private void LoadMovies(string MovieFolderPath)
        {
            BLL.MovieCollection movies = (BLL.MovieCollection)this.lvwMovies.ItemsSource;

            movies.Clear();
            foreach (string directory in System.IO.Directory.GetDirectories(MovieFolderPath))
            {
                BLL.Movie movie = new BLL.Movie();
                movie.Path = directory;
                movie.Name = System.IO.Path.GetFileName(directory);

                movies.Add(movie);
            }
        }

        public void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            mshtml.IHTMLDocument2 document = this.WebBrowser.Document as mshtml.IHTMLDocument2;
            string pageHTML = document.body.innerHTML;

            if (pageHTML.Contains("<INPUT class=button value=Login type=submit name=userlogin>"))
            {
                this.lblStatus.Content = "Not logged in";
                this.lblStatus.Visibility = Visibility.Visible;

                return;
            }
            else
            {
                this.lblStatus.Visibility = Visibility.Hidden;
            }

            if (pageHTML.Contains("<TD><B>Dvdid: </B>"))
            {
                int startIndex = pageHTML.IndexOf("<TD><B>Dvdid: </B>") + 18;
                int endIndex = pageHTML.IndexOf("</TD></TR>\r\n<TR>\r\n<TD><B>Downloads: </B>");

                string dvdid = pageHTML.Substring(startIndex, endIndex - startIndex);

                this.lblWebDvdIdValue.Content = dvdid;
            }
            else
            {
                this.lblWebDvdIdValue.Content = string.Empty;
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (this.lvwMovies.SelectedItems.Count == 0)
            {
                return;
            }

            this.MovieSearch();
        }

        private void MovieSearch()
        {
            string searchString = this.txtSearchCriteria.Text;
            
            searchString = searchString.Replace(" ", "+");
            searchString = searchString.Replace("'", "");
            searchString = System.Web.HttpUtility.UrlEncode(searchString);

            this.WebBrowser.Navigate(new Uri(string.Format(this.searchurl, searchString)));
        }

        private void lvwMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lvwMovies.SelectedItems.Count == 0)
            {
                return;
            }

            BLL.Movie movie = (BLL.Movie)this.lvwMovies.SelectedItems[0];

            this.txtMovieTitle.Text = movie.Name;
            this.txtSearchCriteria.Text = movie.Name;

            this.EnableDvdIdDeleteButton(movie);
        }

        private void lvwMovies_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.lvwMovies.SelectedItems.Count == 0)
            {
                return;
            }

            BLL.Movie movie = (BLL.Movie)this.lvwMovies.SelectedItems[0];

            this.txtMovieTitle.Text = movie.Name;
            this.txtSearchCriteria.Text = movie.Name;

            this.EnableDvdIdDeleteButton(movie);

            this.MovieSearch();
        }

        private void EnableDvdIdDeleteButton(BLL.Movie Movie)
        {
            foreach (string file in System.IO.Directory.GetFiles(Movie.Path))
            {
                if (file.Contains("dvdid.xml"))
                {
                    this.lblCurrentDvdIdValue.Content = UTIL.Xml.ReadDvdId(file);
                    this.btnDeleteDvdId.IsEnabled = true;
                    break;
                }
                else
                {
                    this.lblCurrentDvdIdValue.Content = string.Empty;
                    this.btnDeleteDvdId.IsEnabled = false;
                }
            }
        }

        private void btnWriteDvdId_Click(object sender, RoutedEventArgs e)
        {
            if (this.lvwMovies.SelectedItems.Count == 0)
            {
                return;
            }

            if (this.lblWebDvdIdValue.Content == null || this.lblWebDvdIdValue.Content.ToString().Length == 0)
            {
                MessageBox.Show("There is no DvdId to write.\r\n\r\nAre you signed into DvdXml.com?");
                return;
            }

            BLL.Movie movie = (BLL.Movie)this.lvwMovies.SelectedItems[0];

            bool writeSuccess = false;

            string currentDvdIdPath = string.Empty;
            foreach (string file in System.IO.Directory.GetFiles(movie.Path))
            {
                if (file.Contains("dvdid.xml"))
                {
                    currentDvdIdPath = file;
                    break;
                }
            }

            if (currentDvdIdPath.Length > 0)
            {
                MessageBoxResult overwriteResult = MessageBox.Show("An existing DVDID File already exists.\r\n\r\nOverwrite?", "DVDID Tool", MessageBoxButton.YesNo);

                if (overwriteResult == MessageBoxResult.No)
                {
                    return;
                }
            }
            else
            {
                currentDvdIdPath = string.Format("{0}\\{1}.dvdid.xml", movie.Path, movie.Name);
            }

            writeSuccess = UTIL.Xml.WriteDVDIDXml(this.txtMovieTitle.Text, this.lblWebDvdIdValue.Content.ToString(), currentDvdIdPath);

            this.EnableDvdIdDeleteButton(movie);

            if (!writeSuccess)
            {
                MessageBox.Show("Failed to write DvdId Xml");
                return;
            }
        }

        private void btnDeleteDvdId_Click(object sender, RoutedEventArgs e)
        {
            if (this.lvwMovies.SelectedItems.Count == 0)
            {
                return;
            }

            BLL.Movie movie = (BLL.Movie)this.lvwMovies.SelectedItems[0];

            string currentDvdIdPath = string.Empty;
            foreach (string file in System.IO.Directory.GetFiles(movie.Path))
            {
                if (file.Contains("dvdid.xml"))
                {
                    currentDvdIdPath = file;
                    break;
                }
            }

            if (currentDvdIdPath.Length > 0)
            {
                MessageBoxResult overwriteResult = MessageBox.Show("Are you sure you want to delete the existing dvdid.xml file?", "DVDID Tool", MessageBoxButton.YesNo);

                if (overwriteResult == MessageBoxResult.No)
                {
                    return;
                }

                try
                {
                    System.IO.File.Delete(currentDvdIdPath);
                    this.EnableDvdIdDeleteButton(movie);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            if (this.lblCurrentDvdIdValue.Content.ToString().Length == 0)
            {
                MessageBox.Show("Cannot edit the DvdInfoCache file for this movie.\r\n\r\nNo DvdId has been saved.");
                return;
            }

            EditWindow editWindow = new EditWindow();
            editWindow.DvdId = this.lblCurrentDvdIdValue.Content.ToString();
            editWindow.ShowDialog();
        }
    }
}
